package com.zhuliwei.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zhuliwei.domain.vo.WeatherResponse;
import com.zhuliwei.service.WeatherDataService;
import jakarta.annotation.Resource;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
public class WeatherDataServiceImpl implements WeatherDataService {
 
    @Resource
    private RestTemplate restTemplate;
 
    private final String WEATHER_API = "https://v0.yiketianqi.com/api?unescape=1&version=v91&appid=43656176&appsecret=I42og6Lm&ext=";
 
    @Override
    public String getDataByCityId(String cityId) {
        String uri = WEATHER_API + "&cityid=" + cityId;
        return this.doGetWeatherData(uri);
    }
 
    @Override
    public String getDataByCityName(String cityName) {
        String uri = WEATHER_API + "&city=" + cityName;
        return this.doGetWeatherData(uri);
    }
 
    private String doGetWeatherData(String uri) {
        ResponseEntity<String> response = restTemplate.getForEntity(uri, String.class);
        String strBody = null;
 
        if (response.getStatusCodeValue() == 200) {
            strBody = response.getBody();
        }
 
        ObjectMapper mapper = new ObjectMapper();
        WeatherResponse weather = null;
 
        try {
            weather = mapper.readValue(strBody, WeatherResponse.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
 
        return strBody;
    }
 
}